package com.smartalarmclock.UI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.smartalarmclock.Logic.AcManager;
import com.smartalarmclock.Model.IProfile;

import android.R.bool;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass. Activities that
 * contain this fragment must implement the
 * {@link ProfileFragment.OnFragmentInteractionListener} interface to handle
 * interaction events. Use the {@link ProfileFragment#newInstance} factory
 * method to create an instance of this fragment.
 * 
 */
public class ProfileFragment extends Fragment {
	private static final int UPDATE_PROFILES_LIST_REQUEST = 1;
	public static final int UPDATE_PROFILES_NEEDED_RESULT = 2;
	public static final int UPDATE_PROFILES_NOT_NEEDED_RESULT = 3;
	
	// TODO: Rename parameter arguments, choose names that match
	// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
	private static final String ARG_PARAM1 = "param1";
	private static final String ARG_PARAM2 = "param2";

	private ArrayList<IProfile> m_ActiveProfiles = new ArrayList<IProfile>();
	private List<ProfileItemDetails> m_ProfilesItemDetailsList = new ArrayList<ProfileItemDetails>();
	private ListView m_ProfileListView;
	
	private OnFragmentInteractionListener mListener;
	

	/**
	 * Use this factory method to create a new instance of this fragment using
	 * the provided parameters.
	 * 
	 * @param param1
	 *            Parameter 1.
	 * @param param2
	 *            Parameter 2.
	 * @return A new instance of fragment ProfileFragment.
	 */
	// TODO: Rename and change types and number of parameters
	public static ProfileFragment newInstance(String param1, String param2) {
		ProfileFragment fragment = new ProfileFragment();
		Bundle args = new Bundle();
		args.putString(ARG_PARAM1, param1);
		args.putString(ARG_PARAM2, param2);
		fragment.setArguments(args);
		return fragment;
	}

	public ProfileFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null) {
			getArguments().getString(ARG_PARAM1);
			getArguments().getString(ARG_PARAM2);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.profile_screen, container, false);

        // set listener for buttons
        final ImageButton newProfileButton = (ImageButton)rootView.findViewById(R.id.imageButton_profile_new);
        newProfileButton.setOnClickListener(newProfileButtonClickListener);
        
        m_ProfileListView = (ListView)rootView.findViewById(R.id.listView_profile_list);
        m_ProfileListView.setOnItemClickListener(profileListItemClickListener);
        
        // update the active profiles list from the AcManager
        updateActiveProfilesListItems(rootView.getContext(), true);
        
        return rootView;
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (OnFragmentInteractionListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement OnFragmentInteractionListener");
		}
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}
	
    private void updateActiveProfilesListItems(Context context, Boolean createAdapter)
    {
    	// clear both lists
    	m_ActiveProfiles.clear();
    	m_ProfilesItemDetailsList.clear();
    	
    	// get active profiles from AcManager
		// ToDo: fix stubs...
    	m_ActiveProfiles = AcManager.GetInstance().GetActiveProfiles(this.getActivity());
		
		// build a list with all active profiles list items
		for (IProfile activeProfile : m_ActiveProfiles)
		{
			m_ProfilesItemDetailsList.add(new ProfileItemDetails(activeProfile));
		}
		
        // set profile list adapter and items on-click listener
        ArrayAdapter<ProfileItemDetails> arrayAdapter;
        if (createAdapter)
        {
        	arrayAdapter = new ProfileArrayAdapter(context, m_ProfilesItemDetailsList);
        }
        else
        {
        	arrayAdapter = (ArrayAdapter<ProfileItemDetails>)m_ProfileListView.getAdapter();
        } 
        m_ProfileListView.setAdapter(arrayAdapter);
        arrayAdapter.notifyDataSetChanged();
    }
    
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	if (UPDATE_PROFILES_LIST_REQUEST == requestCode)
    	{
    		if (UPDATE_PROFILES_NEEDED_RESULT == resultCode)
    		{
          		// update the active profiles from the AcManager
          		updateActiveProfilesListItems(this.getView().getContext(), false);
    		}
    	}
    }
	
    private OnItemClickListener profileListItemClickListener = new OnItemClickListener() {
     	private static final String TAG = "OnItemClickListener";

        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id)
        {
    	    Log.v(TAG, "Clicked on profile");

        	final IProfile item = ((ProfileItemDetails)parent.getItemAtPosition(position)).getProfile();
          
        	// start profile details activity for editing a profile 
      		Intent newProfileActivityIntent = new Intent(view.getContext(), CreateNewProfileActivity.class);
      		newProfileActivityIntent.putExtra(Messages.PROFILE_DETAILS_IS_NEW, false);
      		newProfileActivityIntent.putExtra(Messages.PROFILE_DETAILS_PROFILE_ID, item.GetId());
      		startActivityForResult(newProfileActivityIntent, UPDATE_PROFILES_LIST_REQUEST);
        }
    };
	
    private OnClickListener newProfileButtonClickListener = new OnClickListener()
    {
    	@Override
        public void onClick(View v)
        {   
        	// start profile details activity for a new profile 
        	Intent newProfileActivityIntent = new Intent(v.getContext(), CreateNewProfileActivity.class);
        	newProfileActivityIntent.putExtra(Messages.PROFILE_DETAILS_IS_NEW, true);
        	newProfileActivityIntent.putExtra(Messages.PROFILE_DETAILS_PROFILE_ID, -1);
        	startActivityForResult(newProfileActivityIntent, UPDATE_PROFILES_LIST_REQUEST);
        }
    };
	
	private class ProfileArrayAdapter extends ArrayAdapter<ProfileItemDetails>
    {
    	private LayoutInflater l_Inflater;
    	HashMap<IProfile, Integer> m_IdMap = new HashMap<IProfile, Integer>();
    	
    	public ProfileArrayAdapter(Context context, List<ProfileItemDetails> activeProfileItems)
    	{
    		super(context, R.layout.profile_list_item, activeProfileItems);
    		
    		l_Inflater = LayoutInflater.from(context);
    		
    		// set profiles in id-map
    		int i = 0;
    		for (ProfileItemDetails profileItem : activeProfileItems)
    		{
    			m_IdMap.put(profileItem.getProfile(), i++);
    		}
    	}
    	
    	public View getView(int position, View convertView, ViewGroup parent) {
    		ViewHolder holder;
    		if (convertView == null) {
    			convertView = l_Inflater.inflate(R.layout.profile_list_item, null);
    			holder = new ViewHolder();
    			holder.txt_itemName = (TextView)convertView.findViewById(R.id.profile_list_item_text);
    			holder.itemImage = (ImageView)convertView.findViewById(R.id.profile_list_item_image);

    			convertView.setTag(holder);
    		} else {
    			holder = (ViewHolder) convertView.getTag();
    		}
    		
    		holder.txt_itemName.setText(getItem(position).getName());
    		holder.itemImage.setImageResource(R.drawable.profile);

    		return convertView;
    	}
    	
    	@Override
    	public long getItemId(int position)
    	{
    		ProfileItemDetails item = getItem(position);
    		return m_IdMap.get(item.getProfile());
    	}
    	
    	@Override
    	public boolean hasStableIds()
    	{
    		return true;
    	}
    }

    static class ViewHolder
    {
		TextView txt_itemName;
		ImageView itemImage;
	}
    
    public class ProfileItemDetails
    {
    	private IProfile m_Profile = null;
    	
    	public ProfileItemDetails(IProfile i_Profile)
    	{
    		m_Profile = i_Profile;
    	}
    	
    	public String getName()
    	{
    		return m_Profile.GetName();
    	}
    	
    	public IProfile getProfile()
    	{
    		return m_Profile;
    	}
    }
}
